<template>
  <view class="my-coupon" :style="{ '--themeColor': themeColor }">
    <nav-bar
      title="我的优惠券"
      bgColor="#f7f7f7"
      :showBorder="true"
      borderColor="#ececec"
    />
    <view class="tab">
      <view
        :class="['tab-one', item.value === aciveTab ? 'active' : '']"
        v-for="(item, index) in tabList"
        :key="index"
        @click="changeTab(item.value)"
        >{{ item.title }}</view
      >
    </view>
    <scroll-view
      class="list"
      scroll-y
      refresher-enabled="true"
      @refresherpulling="pulling"
      :refresher-triggered="triggered"
      @scrolltolower="scrolltolower"
      @refresherrefresh="resetList"
    >
      <coupon-content
        v-for="(item, index) in list"
        :key="index"
        :couponContet="item"
        :location="location"
      />
      <list-enpty v-if="list.length <= 0" />
      <view class="no-data" v-else>{{
        total === list.length ? "没有更多了～" : "上滑加载更多"
      }}</view>
    </scroll-view>
    <view class="bottom-fixed">
      <view class="look" @click="$myTool.jumpPage('loseCoupon')"
        >查看已经失效的券></view
      >
      <view class="btn" @click="$myTool.jumpPage('pullCoupon')">领券</view>
    </view>
  </view>
</template>

<script>
import { mapState } from "vuex";
import couponContent from "@/components/pageComponents/sp-coupon/coupon-content/index.vue";
import MescrollMixin from "@/uni_modules/mescroll-uni/components/mescroll-uni/mescroll-mixins.js";
import { getMyCoupon } from "@/service/api/sp-coupon/index";
import dayjs from "dayjs";

export default {
  mixins: [MescrollMixin], // 使用mixin
  components: {
    couponContent,
  },
  data() {
    return {
      tabList: [
        { title: "全部", value: 1 },
        // { title: "失效", value: 2 },
        { title: "即将过期", value: 3 },
      ],
      aciveTab: 1,
      list: [],
      queryParams: {
        pageNum: 1,
        pageSize: 10,
        status: 1,
      },
      location: {
        longitude: "",
        latitude: "",
      },
      triggered: false,
      total: 0,
    };
  },
  computed: {
    ...mapState("sp-common/base", ["themeColor"]),
  },
  mounted() {
    this.pulling();
  },
  methods: {
    changeTab(val) {
      if (val == this.aciveTab) return;
      this.aciveTab = val;
      this.queryParams.status = val;
      this.pulling();
    },
    getCouponList() {
      let {
        queryParams,
        queryParams: { pageNum },
      } = this;
      getMyCoupon(queryParams).then((res) => {
        setTimeout(() => {
          this.triggered = false;
        }, 500);
        let { total } = res;
        this.total = total;
        let list = this.toUpperCaseFunc(res.list);
        list = this.expireAfterFunc(list);
        this.list =
          pageNum == 1
            ? this.parseCouponList(list)
            : this.list.concat(this.parseCouponList(list));
      });
    },

    resetList() {
      this.triggered = true;
      this.queryParams.pageNum = 1;
      this.getCouponList();
    },
    parseCouponList(list) {
      list = list.map((value) => {
        let customerCoupon = value.customerCoupon;
        let nowTime = dayjs();
        let day = dayjs(customerCoupon.expireTime).diff(nowTime, "day");
        let effective = dayjs(customerCoupon.effectiveTime).diff(
          nowTime,
          "day"
        );
        if (day === 0) {
          value.expireTag = "今天即将过期";
        }
        if (day < 0) {
          value.expireTag = "已过期";
        }
        value.day = day;
        value.effective = effective;
        value.dillExpireTime = dayjs(customerCoupon.expireTime)
          .subtract(1, "second")
          .format("YYYY-MM-DD");
        value.effectiveTime = dayjs(customerCoupon.effectiveTime).format(
          "YYYY-MM-DD"
        );
        if (customerCoupon.couponType === "CASH") {
          let reduceCost = customerCoupon.reduceCost / 100;
          let reduceCostArr = reduceCost.toString().split(".");
          value.balanceBefore = reduceCostArr[0];
          if (reduceCostArr.length > 1) {
            value.afterBalance = reduceCostArr[1];
          }
        } else if (customerCoupon.couponType === "DISCOUNT") {
          //处理折扣字段
          let reduceDiscount = customerCoupon.discount / 10;
          let reduceDiscountArr = reduceDiscount.toString().split(".");
          if (reduceDiscountArr.length > 1) {
            value.discountBefore = reduceDiscountArr[0];
            value.discountAfter = reduceDiscountArr[1];
          } else {
            value.discountBefore = reduceDiscountArr[0];
            value.discountAfter = 0;
          }
        }
        return value;
      });
      return list;
    },
    //兼容新 旧券 大小写和类型问题

    toUpperCaseFunc(list) {
      if (list.length > 0) {
        let str = /^8128\d{16,20}$/;
        list.forEach((item) => {
          // extend:1新券，extend:2 旧券
          if (str.test(item.customerCoupon.couponCode)) {
            item.extend = 1;
          } else {
            item.extend = 2;
          }
          let type = item.customerCoupon.couponType;
          item.type = type;
          if (
            type == "cash" ||
            type == "cash_wx_busi" ||
            type == "cash_wx_pay"
          ) {
            item.customerCoupon.couponType = "CASH";
          } else if (type == "discount" || type == "discount_wx_busi") {
            item.customerCoupon.couponType = "DISCOUNT";
          } else if (type == "exchange") {
            item.customerCoupon.couponType = "GENERAL";
          }
          item.customerCoupon.couponType =
            item.customerCoupon.couponType.toUpperCase();
        });
        return list;
      } else {
        return [];
      }
    },
    //计算即将过期的券
    expireAfterFunc(list) {
      let day1 = Date.parse(new Date());
      let arr = [];
      if (list.length > 0) {
        list.forEach((item) => {
          if (item.customerCoupon) {
            let expireTime = item.customerCoupon.expireTime;
            let day2 = new Date(expireTime.replace(/-/g, "/")).getTime();
            item.after = (day2 - day1) / (1000 * 60 * 60 * 24);
            if (item.after < 30) {
              arr.push(item);
            }
          }
        });
        // this.setData({
        //   pastCouponList: arr,
        // });
        return list;
      }

      return [];
    },
    scrolltolower() {
      let { total, list } = this;
      if (total == list.length) return;
      this.queryParams.pageNum++;
      this.getCouponList();
    },
    pulling() {
      this.triggered = true;
    },
  },
};
</script>

<style>
page {
  background-color: #f7f7f7;
  width: 100%;
  height: 100vh;
}
</style>
<style lang="scss" scoped>
.no-data {
  padding: 25rpx 0;
  text-align: center;
  font-size: 27rpx;
  color: #888;
}
.my-coupon {
  width: 100%;
  display: flex;
  flex-direction: column;
  height: calc(100% - 110px);
  .tab {
    display: flex;
    padding: 30rpx 20rpx;
    .tab-one {
      height: 56rpx;
      padding: 0 27rpx;
      display: flex;
      font-size: 29rpx;
      color: #888888;
      align-items: center;
      background: #fff;
      margin-left: 25rpx;
      border-radius: 28rpx;
    }
    .active {
      background: var(--theme-color) !important;
      color: #fff;
    }
  }
  .list {
    padding: 0 20rpx;
    width: calc(100% - 40rpx);
    flex: 1;
    overflow-y: scroll;
  }
  .bottom-fixed {
    position: fixed;
    bottom: 0px;
    left: 0px;
    width: 100%;
    padding: 20rpx 0rpx 50rpx;
    display: flex;
    flex-direction: column;
    align-items: center;
    background-color: #f7f7f7;
    .look {
      font-size: 27rpx;
      color: var(--theme-color);
    }
    .btn {
      background: var(--theme-color);
      border-radius: 40rpx;
      height: 80rpx;
      font-size: 29rpx;
      color: #ffffff;
      margin-top: 35rpx;
      width: calc(100% - 140rpx);
      display: flex;
      align-items: center;
      justify-content: center;
    }
  }
}
</style>
